<template>
  <div class="detail-container">
    <NavBar>
      <template #default> 详情 </template>
    </NavBar>

    <div class="product-detail">
      <div class="product-image">
        <img
          v-if="productInfo.mainImage"
          :src="productInfo.mainImage"
          :alt="productInfo.productName"
        />
        <img
          v-else
          src="https://via.placeholder.com/400x300?text=No+Image"
          alt="无图片"
        />
      </div>

      <div class="product-info-block">
        <h2 class="product-name">{{ productInfo.productName }}</h2>
        <p class="product-price">
          ¥{{ productInfo.price }}
          <span v-if="productInfo.originalPrice" class="original-price"
            >¥{{ productInfo.originalPrice }}</span
          >
        </p>
        <p class="product-desc">
          {{ productInfo.detail || "暂无详细描述。" }}
        </p>
      </div>

      <div class="product-reviews">
        <ReviewsView
          :showPopup="showPopup"
          @update:showPopup="showPopup = $event"
        />

        <div class="review-list">
          <div class="review-item">
            <div class="user-info">
              <!-- <img src="https://via.placeholder.com/40" class="avatar" /> -->
              <span class="username">用户1234</span>
            </div>
            <div class="review-content">
              <div class="rating">
                <el-icon><StarFilled /></el-icon>
                <el-icon><StarFilled /></el-icon>
                <el-icon><StarFilled /></el-icon>
                <el-icon><StarFilled /></el-icon>
                <el-icon><Star /></el-icon>
                <span class="rating-text">4.0</span>
              </div>
              <p class="review-text">质量很好，穿着很舒服，下次还会购买</p>
              <div class="review-images">
                <!-- <img src="https://via.placeholder.com/80" alt="评价图片" />
                <img src="https://via.placeholder.com/80" alt="评价图片" /> -->
              </div>
              <p class="review-time">2023-05-15</p>
            </div>
          </div>

          <div class="review-item">
            <div class="user-info">
              <!-- <img src="https://via.placeholder.com/40" class="avatar" /> -->
              <span class="username">买家5678</span>
            </div>
            <div class="review-content">
              <div class="rating">
                <el-icon><StarFilled /></el-icon>
                <el-icon><StarFilled /></el-icon>
                <el-icon><StarFilled /></el-icon>
                <el-icon><StarFilled /></el-icon>
                <el-icon><StarFilled /></el-icon>
                <span class="rating-text">5.0</span>
              </div>
              <p class="review-text">非常满意，物超所值！</p>
              <p class="review-time">2023-05-10</p>
            </div>
          </div>
        </div>
      </div>

      <div class="product-detail-images">
        <div class="section-title">
          <h3>商品详情</h3>
        </div>
        <template
          v-if="productInfo.subImages && productInfo.subImages.length > 0"
        >
          <img
            v-for="(img, idx) in productInfo.subImages"
            :key="idx"
            :src="img"
            :alt="'商品详情图片 ' + (idx + 1)"
          />
        </template>
        <template v-else-if="productInfo.mainImage">
          <img :src="productInfo.mainImage" alt="商品详情图片" />
        </template>
        <div v-else class="no-detail-images">暂无详情图片。</div>
      </div>
    </div>

    <div class="action-bar">
      <div class="action-icons">
        <div class="action-item">
          <el-icon><ChatDotRound /></el-icon>
          <span>客服</span>
        </div>
        <router-link to="/shopcart" class="cart-link">
          <div class="action-item">
            <el-icon><ShoppingCart /></el-icon>
            <span>购物车</span>
          </div>
        </router-link>
      </div>
      <div class="action-buttons">
        <button class="add-cart" @click="handleAddToCart">加入购物车</button>
        <button class="buy-now">立即购买</button>
      </div>
    </div>
  </div>
</template>

<script setup>
import NavBar from "../../components/common/NavBar.vue";
import { useRoute } from "vue-router";
import { ref, onMounted } from "vue";
import { ElMessage } from "element-plus";
import {
  ChatDotRound,
  ShoppingCart,
  StarFilled,
  Star,
} from "@element-plus/icons-vue";

import ReviewsView from "./ReviewsView.vue";
import { addItemToCart } from "@/api/CartApi";
// import { useCartStore } from "@/stores/cartStore";

const route = useRoute();
const productInfo = ref({});
const showPopup = ref(false);

// const cartStore = useCartStore();

if (route.query.item) {
  try {
    const decodedItemString = route.query.item;
    const parsedItem = JSON.parse(decodedItemString);
    productInfo.value = parsedItem;

    if (
      typeof productInfo.value.subImages === "string" &&
      productInfo.value.subImages
    ) {
      productInfo.value.subImages = productInfo.value.subImages
        .replace(/\\/g, "/")
        .split(",");
    } else {
      productInfo.value.subImages = [];
    }
  } catch (e) {
    console.error("Failed to parse product item from route query:", e);
    productInfo.value = {};
  }
} else {
  console.warn(
    "No 'item' query parameter found in route. Displaying empty product info."
  );
  productInfo.value = {};
}

onMounted(() => {
  // cartStore.fetchCartItems();
});

const handleAddToCart = async () => {
  if (!productInfo.value || !productInfo.value.productId) {
    console.warn("Product information not loaded yet. Cannot add to cart.");
    ElMessage.warning("商品信息加载中，请稍后再试。");
    return;
  }
  try {
    // 关键修改：在发送前，将 subImages 数组重新转换回字符串
    const productInfoToSend = { ...productInfo.value }; // 创建一个副本，避免修改原始数据
    if (Array.isArray(productInfoToSend.subImages)) {
      productInfoToSend.subImages = productInfoToSend.subImages.join(",");
    }

    const productDataForCart = {
      productInfo: productInfoToSend,
      quantity: 1,
    };
    await addItemToCart(productDataForCart);

    // ElMessage.success('已添加到购物车！'); // 可以选择性地添加成功提示
  } catch (error) {
    console.error("Error during add to cart process in DetailView:", error);
    ElMessage.error("添加到购物车失败，请稍后再试。"); // 添加失败提示
  }
};
</script>

---

<style scoped>
.detail-container {
  background-color: #f7f5f5;
  /* 确保底部留出足够的空间给固定操作栏 */
  padding-bottom: 75px; /* 操作栏高度65px + 一些额外空间 */
  min-height: 100vh; /* 确保内容不足时页面也能撑满视口，让fixed定位生效 */
  display: flex; /* 使用flex布局让内容在顶部，底部固定栏在底部 */
  flex-direction: column;
}

.product-detail {
  flex-grow: 1; /* 让商品详情内容区域填充可用空间 */
  padding-bottom: 10px; /* 确保内容和底部固定栏之间有间隔 */
}

.product-image img {
  width: 100%;
  height: 300px;
  object-fit: contain;
  display: block;
  background-color: #fff;
  border-bottom: 1px solid #eee;
}

.product-info-block {
  padding: 10px;
  padding-top: 5px;
  padding-bottom: 5px;
  background-color: #fff;
  margin-bottom: 5px;
  border-radius: 10px;
  border: 1px solid #f0eeee;
}

.product-name {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 10px;
  line-height: 1.4;
}

.product-price {
  color: #ff5000;
  font-size: 22px;
  font-weight: bold;
  margin: 10px 0;
  display: flex;
  align-items: baseline;
}

.product-price .original-price {
  text-decoration: line-through;
  color: #999;
  font-size: 0.7em;
  font-weight: normal;
  margin-left: 10px;
}

.product-desc {
  color: #666;
  font-size: 14px;
  line-height: 1.6;
}

.product-reviews {
  background-color: #fff;
  padding: 15px;
  margin-bottom: 5px;
  border-radius: 10px;
  border: 1px solid #f0f0f0;
}

.section-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.section-title h3 {
  font-size: 16px;
  font-weight: bold;
  margin-left: 10px;
}

.more {
  color: #999;
  font-size: 12px;
}

.review-item {
  padding: 15px 0;
  border-bottom: 1px solid #f0f0f0;
}

.user-info {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  margin-right: 10px;
}

.username {
  font-size: 14px;
  color: #333;
}

.rating {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.rating .el-icon {
  color: #ff9900;
  font-size: 16px;
  margin-right: 3px;
}

.rating-text {
  color: #ff9900;
  font-size: 14px;
  margin-left: 5px;
}

.review-text {
  font-size: 14px;
  color: #333;
  line-height: 1.6;
  margin-bottom: 10px;
}

.review-images {
  display: flex;
  gap: 10px;
  margin-bottom: 10px;
}

.review-images img {
  width: 80px;
  height: 80px;
  border-radius: 4px;
  object-fit: cover;
}

.review-time {
  font-size: 12px;
  color: #999;
}

.product-detail-images {
  background-color: #fff;
  padding: 0;
  border-radius: 10px;
  border: 1px solid #f0f0f0;
  margin-bottom: 10px;
}

.product-detail-images img {
  width: 100%;
  display: block;
  margin-bottom: -1px;
}

.no-detail-images {
  text-align: center;
  padding: 20px;
  color: #999;
  font-size: 14px;
}

/* --- action-bar 样式修改 --- */
.action-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 65px;
  background: #fff;
  /* 确保z-index足够高，避免被其他元素覆盖 */
  z-index: 1000;
  /* 增加阴影使其更明显 */
  box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.1);
  /* 使用Flexbox进行内部布局 */
  display: flex;
  justify-content: space-between; /* 子元素两端对齐 */
  align-items: center; /* 垂直居中 */
  padding: 0 15px; /* 左右内边距 */
  border-top: 1px solid #eee; /* 可选：顶部边框 */
}

.action-icons {
  display: flex;
  gap: 20px; /* 图标之间的间距 */
}

.action-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  color: #666;
  font-size: 12px;
}

.action-item .el-icon {
  font-size: 22px; /* 调整图标大小 */
  margin-bottom: 3px;
}

.cart-link {
  text-decoration: none; /* 移除router-link的下划线 */
  color: inherit; /* 继承父级的字体颜色 */
}

.action-buttons {
  display: flex;
  gap: 10px; /* 按钮之间的间距 */
}

.add-cart,
.buy-now {
  padding: 10px 20px;
  border: none;
  border-radius: 20px;
  font-size: 16px;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.add-cart {
  background-color: #ff9900;
  color: #fff;
}

.add-cart:hover {
  background-color: #e68a00;
}

.buy-now {
  background-color: #ff5000;
  color: #fff;
}

.buy-now:hover {
  background-color: #e64400;
}
</style>